import { TMakeASTNode, CompilerConfig, ExtensionFunction, FunctionEvaluator, PackageInfo, CompilerError, EvaluationContext, VariableScope, PluginSystem, PluginLifecycleEvent, createPluginManager, SwitchStatementNode, CaseClauseNode, DefaultClauseNode, ASTNodeType, BuiltInFunction, FunctionParameter } from './types';
import * as fs from 'fs';
import * as path from 'path';
import { execSync } from 'child_process';

export class TMakeCompiler {
    private config: CompilerConfig;
    private extensions: Map<string, ExtensionFunction> = new Map();
    private functions: Map<string, BuiltInFunction | ExtensionFunction> = new Map();
    private errors: CompilerError[] = [];
    private warnings: string[] = [];
    private currentContext: EvaluationContext;
    private pluginManager: PluginSystem;
    private outputDir: string = 'out';

    constructor() {
        this.config = {
            outputFile: '',
            packages: [],
            compiler: '',
            dynamicLibraries: [],
            sourceFiles: [],
            variables: {},
            resolvedValues: {},
            scopes: [{ name: 'global', variables: {} }],
            mode: 'debug',
            optimizeLevel: 1,
            logLevel: 'info'
        };
        this.currentContext = { variables: this.config.variables };
        this.pluginManager = createPluginManager(this);

        this.pluginManager.emitEvent(PluginLifecycleEvent.BEFORE_INIT);
        this.registerBuiltInFunctions();
        this.registerAdditionalBuiltInFunctions();

        this.initializeDefaultPlugins().catch(err => {
            this.addWarning(`初始化默认插件失败: ${err.message}`);
        });

        this.pluginManager.emitEvent(PluginLifecycleEvent.AFTER_INIT);
    }

    private async initializeDefaultPlugins(): Promise<void> {

        try {
            const extensionsDir = './extensions';
            if (typeof require !== 'undefined') {
                try {
                    const fs = require('fs');
                    const path = require('path');
                    const extensionsPath = path.resolve(__dirname, extensionsDir);
                    if (fs.existsSync(extensionsPath)) {
                        await this.pluginManager.loadPluginsFromDirectory(extensionsPath);
                    }
                } catch (error) {

                }
            }
        } catch (error) {

        }
    }

    public getErrors(): CompilerError[] {
        return this.errors;
    }

    public getWarnings(): string[] {
        return this.warnings;
    }

    private addError(error: CompilerError): void {
        this.errors.push(error);
        if (this.pluginManager) {
            this.pluginManager.emitEvent(PluginLifecycleEvent.ON_ERROR, error);
        }
    }

    private addWarning(warning: string): void {
        this.warnings.push(warning);
        if (this.pluginManager) {
            this.pluginManager.emitEvent(PluginLifecycleEvent.ON_WARNING, warning);
        }
    }
    
    /**
     * 创建统一格式的错误对象
     */
    private createError(type: 'runtime' | 'syntax' | 'lexical', message: string, node?: TMakeASTNode, details?: string): CompilerError {
        return {
            type,
            message,
            line: node?.line,
            column: node?.column,
            details
        };
    }
    
    /**
     * 创建并添加错误，支持从节点获取位置信息
     */
    private createAndAddError(type: 'runtime' | 'syntax' | 'lexical', message: string, node?: TMakeASTNode, error?: Error): void {
        const details = error?.message;
        this.addError(this.createError(type, message, node, details));
    }
    
    /**
     * 处理函数执行错误
     */
    private handleFunctionError(functionName: string, node: TMakeASTNode, error: Error): void {
        this.createAndAddError('runtime' as const, `函数 ${functionName} 执行失败`, node, error);
    }

    registerExtension(extension: ExtensionFunction): void {
        this.extensions.set(extension.name, extension);
        this.functions.set(extension.name, extension);
        
        // 如果没有提供描述信息，添加基本描述
        if (!extension.description) {
            extension.description = `扩展函数 ${extension.name}`;
        }
        if (!extension.parameters) {
            extension.parameters = [];
        }
        if (!extension.returnType) {
            extension.returnType = 'any';
        }
        if (!extension.returnDescription) {
            extension.returnDescription = '函数执行结果';
        }
    }
    
    /**
     * 注册内置函数到函数映射表
     */
    private registerBuiltInFunctions(): void {
        const builtInFunctions: BuiltInFunction[] = [
            {
                name: 'TMake版本',
                description: '设置TMake版本信息',
                parameters: [
                    {
                        name: 'version',
                        type: 'string',
                        description: 'TMake版本号',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的版本号',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.variables.tmakeVersion = params[0];
                    compiler.config.resolvedValues['TMake版本'] = params[0];
                    context.variables.tmakeVersion = params[0];
                    return params[0];
                }
            },
            {
                name: '结绳编译器版本',
                description: '设置结绳编译器版本信息',
                parameters: [
                    {
                        name: 'version',
                        type: 'string',
                        description: '结绳编译器版本号',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的版本号',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.variables.compilerVersion = params[0];
                    compiler.config.resolvedValues['结绳编译器版本'] = params[0];
                    context.variables.compilerVersion = params[0];
                    return params[0];
                }
            },
            {
                name: '设置变量',
                description: '设置一个变量的值',
                parameters: [
                    {
                        name: 'name',
                        type: 'string',
                        description: '变量名称',
                        required: true
                    },
                    {
                        name: 'value',
                        type: 'any',
                        description: '变量值',
                        required: true
                    }
                ],
                returnType: 'any',
                returnDescription: '返回设置的变量值',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const varName = params[0];
                    const varValue = params[1];
                    compiler.config.variables[varName] = varValue;
                    compiler.config.resolvedValues[varName] = varValue;
                    context.variables[varName] = varValue;
                    return varValue;
                }
            },
            {
                name: '设置输出文件',
                description: '设置编译输出文件路径',
                parameters: [
                    {
                        name: 'filePath',
                        type: 'string',
                        description: '输出文件路径',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的输出文件路径',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.outputFile = params[0];
                    compiler.config.resolvedValues['设置输出文件'] = params[0];
                    context.variables.输出文件 = params[0];
                    return params[0];
                }
            },
            {
                name: '设置输出文件夹',
                description: '设置编译输出文件夹路径',
                parameters: [
                    {
                        name: 'dirPath',
                        type: 'string',
                        description: '输出文件夹路径',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的输出文件夹路径',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const outputDir = params[0];
                    compiler.setOutputDir(outputDir);
                    compiler.config.resolvedValues['设置输出文件夹'] = outputDir;
                    context.variables.输出文件夹 = outputDir;
                    return outputDir;
                }
            }
            // 其他内置函数会在后续添加
        ];
        
        // 将内置函数添加到函数映射表
        for (const func of builtInFunctions) {
            this.functions.set(func.name, func);
        }
    }


    public setOutputDir(dir: string): void {
        this.outputDir = dir;

        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
    }


    public getOutputDir(): string {
        return this.outputDir;
    }


    public executeCommand(command: string | string[], cwd?: string): { success: boolean; output: string } {
        const cmdStr = Array.isArray(command) ? command.join(' ') : command;
        try {
            this.log(`执行命令: ${cmdStr}`);

            const output = execSync(cmdStr, {
                encoding: 'utf-8',
                cwd: cwd || process.cwd()
            });

            return { success: true, output };
        } catch (error: any) {
            const errorOutput = error.stderr || error.message;
            this.addError({
                type: 'runtime',
                message: `命令执行失败: ${cmdStr}`,
                details: errorOutput
            });
            return { success: false, output: errorOutput };
        }
    }


    public findFiles(directory: string, pattern: RegExp): string[] {
        const files: string[] = [];

        const walkDir = (dir: string) => {
            const entries = fs.readdirSync(dir);
            for (const entry of entries) {
                const fullPath = path.join(dir, entry);
                const stat = fs.statSync(fullPath);

                if (stat.isDirectory()) {
                    walkDir(fullPath);
                } else if (pattern.test(entry)) {
                    files.push(fullPath);
                }
            }
        };

        if (fs.existsSync(directory)) {
            walkDir(directory);
        }

        return files;
    }


    public log(message: string, level: 'debug' | 'info' | 'warning' | 'error' = 'info'): void {

        const levelPriority: Record<string, number> = { debug: 0, info: 1, warning: 2, error: 3 };

        const currentLogLevel = this.config.logLevel || 'info';
        if (levelPriority[level] >= levelPriority[currentLogLevel]) {
            const timestamp = new Date().toISOString().replace('T', ' ').substring(0, 19);
            const consoleMethod = level === 'debug' ? 'log' : level === 'warning' ? 'warn' : level;

            (console as any)[consoleMethod](`[${timestamp}] [${level.toUpperCase()}] ${message}`);
        }
    }


    public getPluginManager(): PluginSystem {
        return this.pluginManager;
    }

    public loadPlugin(plugin: any): boolean {
        return this.pluginManager.loadPlugin(plugin);
    }

    public async loadPluginFromFile(filePath: string): Promise<boolean> {
        return await this.pluginManager.loadPluginFromFile(filePath);
    }

    public async loadPluginsFromDirectory(dirPath: string): Promise<void> {
        await this.pluginManager.loadPluginsFromDirectory(dirPath);
    }

    public getLoadedPlugins(): Array<{ name: string; version: string; description?: string }> {
        return this.pluginManager.getLoadedPlugins();
    }

    async loadExtensionsFromFile(filePath: string): Promise<void> {
        try {
            if (!fs.existsSync(filePath)) {
                this.addWarning(`扩展文件不存在: ${filePath}`);
                return;
            }


            if (this.pluginManager) {
                const loadedAsPlugin = await this.pluginManager.loadPluginFromFile(filePath);
                if (loadedAsPlugin) {
                    return;
                }
            }

            const extensionModule = require(filePath);
            if (extensionModule.default && typeof extensionModule.default === 'function') {
                extensionModule.default(this);
            }
        } catch (error: any) {
            this.addError({
                type: 'runtime',
                message: `加载扩展文件失败: ${filePath}`,
                details: error.message
            });
        }
    }


    private evaluate(node: TMakeASTNode, context: EvaluationContext = this.currentContext): any {
        if (!node) {
            this.createAndAddError('runtime', '求值节点为 null 或 undefined');
            return null;
        }

        try {
            switch (node.type) {
                case 'string':
                    return node.value;

                case 'number':
                    const numValue = parseFloat(node.value);
                    if (isNaN(numValue)) {
                        this.addWarning(`无效的数字格式: ${node.value}`);
                        return node.value;
                    }
                    return numValue;

                case 'identifier':
                    return this.resolveVariable(node.value, context);

                case 'function_call':
                    return this.executeFunctionCall(node, true, context);

                case 'array':
                    // 假设数组节点使用value属性存储数组元素
                    if ('value' in node && Array.isArray(node.value)) {
                        return node.value.map((element: any, index: number) => {
                            if (typeof element === 'object' && element && element.type) {
                                try {
                                    return this.evaluate(element, context);
                                } catch (error: any) {
                                    this.addWarning(`数组元素 ${index} 求值失败: ${error.message}`);
                                    return null;
                                }
                            }
                            return element;
                        });
                    }
                    return [];

                case 'if_statement':
                    return this.executeIfStatement(node, context);

                case 'switch_statement':
                    return this.executeSwitchStatement(node as SwitchStatementNode, context);

                case 'error':
                    this.addWarning(`遇到错误节点: ${node.value}`);
                    return null;

                case 'empty':
                    return null;

                default:
                    return node.rawValue || node.value;
            }
        } catch (error: any) {
            this.createAndAddError('runtime', `表达式求值失败: ${node.type}`, node, error);
            return null;
        }
    }

    /**
     * 执行switch语句（假如/是）
     */
    private executeSwitchStatement(node: SwitchStatementNode, context: EvaluationContext): any {
        try {
            if (!node) {
                this.createAndAddError('runtime', 'switch语句节点为null或undefined');
                return null;
            }
            
            // 计算表达式值
            let expressionValue = null;
            if (node.expression) {
                expressionValue = this.evaluate(node.expression, context);
            } else {
                this.addWarning('switch语句缺少表达式');
                return null;
            }
            
            // 查找匹配的case
            if (Array.isArray(node.cases)) {
                for (const caseClause of node.cases) {
                    // 检查是否为case_clause类型
                    if (caseClause.type === ASTNodeType.CASE_CLAUSE && caseClause.test) {
                        let testValue = null;
                        try {
                            testValue = this.evaluate(caseClause.test, context);
                        } catch (error: any) {
                            this.addWarning(`case条件求值失败: ${error.message}`);
                            continue;
                        }
                        
                        // 使用宽松的相等比较
                        if (testValue == expressionValue) {
                            // 执行匹配的case分支中的所有语句
                            if (Array.isArray(caseClause.consequent)) {
                                for (const statement of caseClause.consequent) {
                                    const result = this.evaluate(statement, context);
                                    if (result !== undefined) return result;
                                }
                            }
                            return;
                        }
                    }
                }
            }
            
            // 如果有defaultCase分支且没有匹配的case
            if (node.defaultCase && node.defaultCase.type === ASTNodeType.DEFAULT_CLAUSE) {
                if (Array.isArray(node.defaultCase.consequent)) {
                    for (const statement of node.defaultCase.consequent) {
                        const result = this.evaluate(statement, context);
                        if (result !== undefined) return result;
                    }
                }
            }
        } catch (error: any) {
            this.createAndAddError('runtime', `switch语句执行失败: ${error.message}`, node, error);
        }
        return null;
    }

    private resolveVariable(name: string, context: EvaluationContext): any {
        if (context.variables.hasOwnProperty(name)) {
            return context.variables[name];
        }

        if (context.parent) {
            return this.resolveVariable(name, context.parent);
        }

        if (this.config.variables.hasOwnProperty(name)) {
            return this.config.variables[name];
        }

        this.addWarning(`未定义的变量: ${name}`);
        return name;
    }

    private executeFunctionCall(node: TMakeASTNode, isExpression: boolean = false, context: EvaluationContext = this.currentContext): any {
        if (!node || !node.value) {
            this.createAndAddError('runtime', '无效的函数调用节点');
            return null;
        }

        const functionName = node.value;
        const params = node.params || [];

        const functionContext: EvaluationContext = {
            variables: {},
            parent: context
        };

        const evaluatedParams: any[] = [];
        for (const param of params) {
            try {
                if (param && typeof param === 'object' && param.type) {
                    const evaluated = this.evaluate(param, functionContext);
                    evaluatedParams.push(evaluated);
                } else {
                    evaluatedParams.push(param);
                }
            } catch (error: any) {
                this.addWarning(`参数求值失败，使用原始值: ${error.message}`);
                evaluatedParams.push(param);
            }
        }

        const evaluatedNode: TMakeASTNode = {
            ...node,
            params: evaluatedParams
        };

        try {
            // 从统一的函数映射中查找函数
            if (this.functions.has(functionName)) {
                const func = this.functions.get(functionName)!;
                // 检查是扩展函数还是内置函数，使用不同的调用方式
                let result;
                if ('handler' in func) {
                    // 扩展函数
                    result = func.handler(evaluatedNode, this.config, (node: TMakeASTNode) => this.evaluate(node, functionContext), functionContext);
                } else if ('implementation' in func) {
                    // 内置函数
                    result = func.implementation(evaluatedParams, evaluatedNode, functionContext, this);
                } else {
                    throw new Error(`函数 ${functionName} 缺少执行方法`);
                }

                if (isExpression) {
                    return result;
                }
                return;
            } else {
                // 如果函数不存在，输出警告
                this.addWarning(`未知函数: ${functionName}`);
                return null;
            }
        } catch (error: any) {
            this.handleFunctionError(functionName, node, error);
            return null;
        }
    }

    /**
     * 注册其他内置函数（不在构造函数中注册的额外函数）
     * 这些函数可能依赖于编译器的其他方法
     */
    private registerAdditionalBuiltInFunctions(): void {
        const additionalFunctions: BuiltInFunction[] = [
            {
                name: '设置绳包目录',
                description: '设置绳包目录并读取绳包列表',
                parameters: [
                    {
                        name: 'packageDir',
                        type: 'string',
                        description: '绳包目录路径',
                        required: true
                    }
                ],
                returnType: 'PackageInfo[]',
                returnDescription: '返回读取的绳包列表',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const packageDir = params[0];
                    const packages = compiler.readPackageList(packageDir);
                    compiler.config.packages = packages;
                    compiler.config.resolvedValues['设置绳包目录'] = packages;
                    context.variables.绳包目录 = packages;
                    return packages;
                }
            },
            {
                name: '设置编译器',
                description: '设置使用的编译器路径',
                parameters: [
                    {
                        name: 'compilerPath',
                        type: 'string',
                        description: '编译器路径',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的编译器路径',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.compiler = params[0];
                    compiler.config.resolvedValues['设置编译器'] = params[0];
                    context.variables.编译器 = params[0];
                    return params[0];
                }
            },
            {
                name: '链接动态库',
                description: '添加需要链接的动态库',
                parameters: [
                    {
                        name: 'libraryPath',
                        type: 'string',
                        description: '动态库路径',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回添加的动态库路径',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.dynamicLibraries.push(params[0]);
                    compiler.config.resolvedValues['链接动态库'] = params[0];
                    return params[0];
                }
            },
            {
                name: '编译程序',
                description: '设置要编译的源文件列表',
                parameters: [
                    {
                        name: 'files',
                        type: 'string[] | string',
                        description: '源文件路径或路径数组',
                        required: true
                    }
                ],
                returnType: 'string[]',
                returnDescription: '返回完整的源文件列表（包括绳包文件）',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const projectFiles = Array.isArray(params[0]) ? params[0] : [params[0]];
                    const packageFiles = compiler.getAllPackageTFiles();
                    compiler.config.sourceFiles = [...projectFiles, ...packageFiles];
                    compiler.config.resolvedValues['编译程序'] = compiler.config.sourceFiles;
                    context.variables.源文件列表 = compiler.config.sourceFiles;
                    return compiler.config.sourceFiles;
                }
            },
            {
                name: '平台为Linux',
                description: '检查当前平台是否为Linux',
                parameters: [],
                returnType: 'boolean',
                returnDescription: '如果是Linux平台返回true，否则返回false',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const isLinux = process.platform === 'linux' || compiler.config.platformTarget?.toLowerCase() === 'linux';
                    compiler.config.resolvedValues['平台为Linux'] = isLinux;
                    context.variables.平台为Linux = isLinux;
                    return isLinux;
                }
            },
            {
                name: '平台为Windows',
                description: '检查当前平台是否为Windows',
                parameters: [],
                returnType: 'boolean',
                returnDescription: '如果是Windows平台返回true，否则返回false',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const isWindows = process.platform === 'win32' || compiler.config.platformTarget?.toLowerCase() === 'windows';
                    compiler.config.resolvedValues['平台为Windows'] = isWindows;
                    context.variables.平台为Windows = isWindows;
                    return isWindows;
                }
            },
            {
                name: '设置目标平台',
                description: '设置编译目标平台',
                parameters: [
                    {
                        name: 'platform',
                        type: 'string',
                        description: '目标平台名称（如windows、linux等）',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的目标平台',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.platformTarget = params[0];
                    compiler.config.resolvedValues['设置目标平台'] = params[0];
                    context.variables.目标平台 = params[0];
                    return params[0];
                }
            },
            {
                name: '设置优化级别',
                description: '设置编译优化级别',
                parameters: [
                    {
                        name: 'level',
                        type: 'number',
                        description: '优化级别（0-3）',
                        required: true
                    }
                ],
                returnType: 'number',
                returnDescription: '返回实际设置的优化级别',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const level = Number(params[0]);
                    if (isNaN(level) || level < 0 || level > 3) {
                        compiler.addWarning(`优化级别 ${params[0]} 无效，使用默认值 1`);
                        compiler.config.optimizeLevel = 1;
                    } else {
                        compiler.config.optimizeLevel = level;
                    }
                    compiler.config.resolvedValues['设置优化级别'] = compiler.config.optimizeLevel;
                    context.variables.优化级别 = compiler.config.optimizeLevel;
                    return compiler.config.optimizeLevel;
                }
            },
            {
                name: '设置日志级别',
                description: '设置日志输出级别',
                parameters: [
                    {
                        name: 'level',
                        type: 'string',
                        description: '日志级别（debug、info、warning、error）',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的日志级别',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.logLevel = params[0];
                    compiler.config.resolvedValues['设置日志级别'] = params[0];
                    context.variables.日志级别 = params[0];
                    return params[0];
                }
            },
            {
                name: '设置行号表路径',
                description: '设置行号映射表文件路径',
                parameters: [
                    {
                        name: 'path',
                        type: 'string',
                        description: '行号表文件路径',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回设置的行号表路径',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.lineMapPath = params[0];
                    compiler.config.resolvedValues['设置行号表路径'] = params[0];
                    context.variables.行号表路径 = params[0];
                    return params[0];
                }
            },
            {
                name: '启用调试模式',
                description: '启用调试编译模式',
                parameters: [],
                returnType: 'string',
                returnDescription: '返回设置的模式（debug）',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.mode = 'debug';
                    compiler.config.resolvedValues['启用调试模式'] = 'debug';
                    context.variables.调试模式 = true;
                    return 'debug';
                }
            },
            {
                name: '发布模式',
                description: '启用发布编译模式',
                parameters: [],
                returnType: 'string',
                returnDescription: '返回设置的模式（release）',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.mode = 'release';
                    compiler.config.resolvedValues['发布模式'] = 'release';
                    context.variables.发布模式 = true;
                    return 'release';
                }
            },
            {
                name: '硬输出模式',
                description: '启用硬输出编译模式',
                parameters: [],
                returnType: 'string',
                returnDescription: '返回设置的模式（hard-mode）',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    compiler.config.mode = 'hard-mode';
                    compiler.config.resolvedValues['硬输出模式'] = 'hard-mode';
                    context.variables.硬输出模式 = true;
                    return 'hard-mode';
                }
            },
            {
                name: '读取绳包列表',
                description: '读取指定目录下的绳包列表',
                parameters: [
                    {
                        name: 'dirPath',
                        type: 'string',
                        description: '绳包目录路径',
                        required: true
                    }
                ],
                returnType: 'PackageInfo[]',
                returnDescription: '返回读取的绳包列表',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const result = compiler.readPackageList(params[0]);
                    compiler.config.resolvedValues['读取绳包列表'] = result;
                    context.variables.绳包列表 = result;
                    return result;
                }
            },
            {
                name: '读取源文件列表',
                description: '读取指定目录下的源文件列表',
                parameters: [
                    {
                        name: 'dirPath',
                        type: 'string',
                        description: '源文件目录路径',
                        required: true
                    }
                ],
                returnType: 'string[]',
                returnDescription: '返回读取的源文件列表',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const files = compiler.readSourceFileList(params[0]);
                    compiler.config.resolvedValues['读取源文件列表'] = files;
                    context.variables.源文件列表 = files;
                    return files;
                }
            },
            {
                name: '禁用指定lint检查',
                description: '禁用指定的lint检查规则',
                parameters: [
                    {
                        name: 'lintRule',
                        type: 'string',
                        description: '要禁用的lint规则名称',
                        required: true
                    }
                ],
                returnType: 'string',
                returnDescription: '返回禁用的lint规则名称',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    if (!compiler.config.disabledLints) {
                        compiler.config.disabledLints = [];
                    }
                    compiler.config.disabledLints.push(params[0]);
                    compiler.config.resolvedValues['禁用指定lint检查'] = params[0];
                    return params[0];
                }
            },
            // 数组相关函数
            {
                name: '创建数组',
                description: '创建并初始化一个数组变量',
                parameters: [
                    {
                        name: 'arrayName',
                        type: 'string',
                        description: '数组变量名称',
                        required: true
                    },
                    {
                        name: 'initialData',
                        type: 'any[] | any',
                        description: '初始数据（数组或单个值）',
                        required: false,
                        defaultValue: []
                    }
                ],
                returnType: 'any[]',
                returnDescription: '返回创建的数组',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const arrayName = params[0];
                    const initialData = params[1] || [];
                    const arrayValue = Array.isArray(initialData) ? initialData : [initialData];
                    compiler.config.variables[arrayName] = arrayValue;
                    compiler.config.resolvedValues[arrayName] = arrayValue;
                    context.variables[arrayName] = arrayValue;
                    return arrayValue;
                }
            },
            {
                name: '数组长度',
                description: '获取数组的长度',
                parameters: [
                    {
                        name: 'array',
                        type: 'any[]',
                        description: '要获取长度的数组',
                        required: true
                    }
                ],
                returnType: 'number',
                returnDescription: '返回数组的长度',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const array = compiler.evaluate(params[0], context);
                    return Array.isArray(array) ? array.length : 0;
                }
            },
            {
                name: '数组追加',
                description: '向数组追加一个元素',
                parameters: [
                    {
                        name: 'array',
                        type: 'any[]',
                        description: '目标数组',
                        required: true
                    },
                    {
                        name: 'value',
                        type: 'any',
                        description: '要追加的值',
                        required: true
                    }
                ],
                returnType: 'any[]',
                returnDescription: '返回追加元素后的数组',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const targetArray = compiler.evaluate(params[0], context);
                    const appendValue = compiler.evaluate(params[1], context);
                    if (Array.isArray(targetArray)) {
                        targetArray.push(appendValue);
                        return targetArray;
                    }
                    return [];
                }
            },
            {
                name: '数组获取',
                description: '获取数组中指定索引的元素',
                parameters: [
                    {
                        name: 'array',
                        type: 'any[]',
                        description: '目标数组',
                        required: true
                    },
                    {
                        name: 'index',
                        type: 'number',
                        description: '元素索引',
                        required: true
                    }
                ],
                returnType: 'any',
                returnDescription: '返回获取的元素，如果索引无效则返回null',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const getArray = compiler.evaluate(params[0], context);
                    const index = Number(params[1]);
                    if (Array.isArray(getArray) && index >= 0 && index < getArray.length) {
                        return getArray[index];
                    }
                    return null;
                }
            },
            {
                name: '数组设置',
                description: '设置数组中指定索引的元素值',
                parameters: [
                    {
                        name: 'array',
                        type: 'any[]',
                        description: '目标数组',
                        required: true
                    },
                    {
                        name: 'index',
                        type: 'number',
                        description: '元素索引',
                        required: true
                    },
                    {
                        name: 'value',
                        type: 'any',
                        description: '要设置的值',
                        required: true
                    }
                ],
                returnType: 'any',
                returnDescription: '返回设置的值，如果数组无效则返回null',
                implementation: (params: any[], node: TMakeASTNode, context: EvaluationContext, compiler: TMakeCompiler) => {
                    const setArray = compiler.evaluate(params[0], context);
                    const setIndex = Number(params[1]);
                    const setValue = compiler.evaluate(params[2], context);
                    if (Array.isArray(setArray) && setIndex >= 0) {
                        setArray[setIndex] = setValue;
                        return setValue;
                    }
                    return null;
                }
            }
        ];
        
        // 将额外的内置函数添加到函数映射表
        for (const func of additionalFunctions) {
            this.functions.set(func.name, func);
        }
    }
    
    /**
     * 初始化编译器（用于确保所有内置函数都已注册）
     */
    public initialize(): void {
        // 注册额外的内置函数
        this.registerAdditionalBuiltInFunctions();
    }

    private readPackageList(dirPath?: string): PackageInfo[] {
        try {
            // 返回空包列表，避免类型错误
            return [];
        } catch (error: any) {
            this.addWarning(`读取绳包列表失败: ${error.message}`);
            return [];
        }
    }

    /**
     * 执行if语句
     */
    private executeIfStatement(node: TMakeASTNode, context: EvaluationContext): void {
        try {
            const condition = node.params![0];
            const conditionResult = this.evaluate(condition, context);
            if (conditionResult && node.children) {
                for (const child of node.children) {
                    this.evaluate(child, context);
                }
            }
        } catch (error: any) {
            this.createAndAddError('runtime', 'if语句执行失败', node, error);
        }
    }

    private readTFilesFromPackage(packagePath: string): string[] {
        try {
            const tFiles: string[] = [];

            const readDirRecursive = (currentPath: string, basePath: string = packagePath) => {
                try {
                    const items = fs.readdirSync(currentPath);

                    for (const item of items) {
                        const fullPath = path.join(currentPath, item);

                        try {
                            const stat = fs.statSync(fullPath);

                            if (stat.isDirectory()) {
                                readDirRecursive(fullPath, basePath);
                            } else if (typeof item === 'string' && item && item.endsWith('.t')) {
                                const relativePath = path.relative(basePath, fullPath);
                                tFiles.push(relativePath);
                            }
                        } catch (error: any) {
                            this.addWarning(`访问文件失败 ${fullPath}: ${error.message}`);
                        }
                    }
                } catch (error: any) {
                    this.addWarning(`读取目录失败 ${currentPath}: ${error.message}`);
                }
            };

            readDirRecursive(packagePath);
            return tFiles;
        } catch (error: any) {
            this.addWarning(`读取绳包.t文件失败: ${error.message}`);
            return [];
        }
    }

    private getAllPackageTFiles(): string[] {
        const allTFiles: string[] = [];

        for (const pkg of this.config.packages) {
            for (const tFile of pkg.tFiles) {
                const fullPath = path.join(pkg.path, tFile);
                allTFiles.push(fullPath);
            }
        }

        return allTFiles;
    }

    private readSourceFileList(dirPath: string): string[] {
        try {
            if (!fs.existsSync(dirPath)) {
                this.addWarning(`源文件目录不存在: ${dirPath}`);
                return [];
            }

            const sourceFiles: string[] = [];

            const readDirRecursive = (currentPath: string, basePath: string = dirPath) => {
                try {
                    const items = fs.readdirSync(currentPath);

                    for (const item of items) {
                        const fullPath = path.join(currentPath, item);

                        try {
                            const stat = fs.statSync(fullPath);

                            if (stat.isDirectory()) {
                                readDirRecursive(fullPath, basePath);
                            } else if (typeof item === 'string' && item && item.endsWith('.t')) {
                                const relativePath = path.relative(basePath, fullPath);
                                sourceFiles.push(relativePath);
                            }
                        } catch (error: any) {
                            this.addWarning(`访问源文件失败 ${fullPath}: ${error.message}`);
                        }
                    }
                } catch (error: any) {
                    this.addWarning(`读取源文件目录失败 ${currentPath}: ${error.message}`);
                }
            };

            readDirRecursive(dirPath);
            return sourceFiles;
        } catch (error: any) {
            this.addWarning(`读取源文件列表失败: ${error.message}`);
            return [];
        }
    }

    compile(ast: TMakeASTNode[]): { config: CompilerConfig, errors: CompilerError[], warnings: string[] } {
        this.errors = [];
        this.warnings = [];

        try {
            // 读取包列表
            const packages = this.readPackageList();
            if (packages && packages.length > 0) {
                this.config.packages = packages;
            }

            if (this.pluginManager) {
                // 确保所有内置函数都已注册
                this.initialize();
                
                this.pluginManager.emitEvent(PluginLifecycleEvent.BEFORE_COMPILE);


                this.pluginManager.emitEvent(PluginLifecycleEvent.AFTER_PARSE, ast);


                this.pluginManager.emitEvent(PluginLifecycleEvent.BEFORE_TRANSFORM, ast);
            }

            this.currentContext = { variables: this.config.variables };

            for (const node of ast) {
                if (node && node.type === 'function_call' && node.value === '设置变量') {
                    try {
                        this.executeFunctionCall(node, false, this.currentContext);
                    } catch (error) {
                    }
                }
            }


            if (this.pluginManager) {
                this.pluginManager.emitEvent(PluginLifecycleEvent.BEFORE_GENERATE, ast);
            }

            for (const node of ast) {
                try {
                    if (node && node.type === 'function_call') {
                        const result = this.executeFunctionCall(node, false, this.currentContext);
                        if (result !== undefined) {
                            this.config.resolvedValues[node.value] = result;
                        }
                    } else if (node && node.type === 'if_statement') {
                        this.executeIfStatement(node, this.currentContext);
                    } else if (node && node.type === 'switch_statement') {
                        this.executeSwitchStatement(node as SwitchStatementNode, this.currentContext);
                    }
                } catch (error: any) {
                    this.addError({
                        type: 'runtime',
                        message: '执行AST节点失败',
                        line: node?.line,
                        column: node?.column,
                        details: error.message
                    });
                }
            }


            if (this.pluginManager) {
                this.pluginManager.emitEvent(PluginLifecycleEvent.AFTER_TRANSFORM, ast);


                this.pluginManager.emitEvent(PluginLifecycleEvent.AFTER_GENERATE, JSON.stringify(this.config, null, 2));


                this.pluginManager.emitEvent(PluginLifecycleEvent.AFTER_COMPILE, true);
            }

            return { config: this.config, errors: this.errors, warnings: this.warnings };
        } catch (error: any) {

            if (this.pluginManager) {
                this.pluginManager.emitEvent(PluginLifecycleEvent.AFTER_COMPILE, false);
            }

            this.addError({
                type: 'runtime',
                message: '编译过程发生致命错误',
                details: error.message
            });
            return { config: this.config, errors: this.errors, warnings: this.warnings };
        }
    }



    toJSON(): string {
        return JSON.stringify(this.config, null, 2);
    }
}